<template>
  <div class="menu-list">
    <!-- 顶部 -->
    <Row type="flex" class="head-row">
      <i-col :span="7" class="col input-col">
        <!-- 搜索框 -->
        <i-input
          v-model="queryInfo.key"
          clearable
          placeholder="输入搜索内容 按ENTER键搜索..."
          @on-enter="search"
          @on-change="clearInput"
        ></i-input>
      </i-col>
      <i-col class="col">
        <i-button type="primary" @click="showAddModal">添加图片</i-button>
      </i-col>
    </Row>

    <!-- 表格数据 -->
    <i-table border :columns="columns" :data="img_list" class="table"></i-table>

    <!-- 分页 -->
    <Page
      show-sizer
      :total="total"
      show-total
      show-elevator
      :page-size-opts="[5, 10, 15, 20]"
      :page-size="queryInfo.pageSize"
      :current="queryInfo.currentPage"
      @on-change="handlePageChange"
      @on-page-size-change="handelPageSizeChange"
    ></Page>

    <!-- 查看对话框 -->
    <!-- :visible.sync属性无法显示，只能用v-model代替 -->
    <Modal v-model="showMenuDetailVisible" title="详情" @on-ok="checkOk" @on-cancel="checkCancel"></Modal>

    <!-- 添加对话框 -->
    <Modal v-model="showMenuAddVisible" title="添加轮播图" @on-visible-change="addModalVisibleChange">
      <i-form ref="addFormRef" :model="addForm" :rules="addFormRules" :label-width="100">
        <Form-item label="图片标题" prop="text">
          <i-input v-model="addForm.text" placeholder="请输入标题"></i-input>
        </Form-item>
        <Form-item label="上传图片">
          <Upload
            action="http://192.168.56.1:9990/api/v1/admin/adv/upload"
            :format="['jpg','jpeg','png']"
            :max-size="2048"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :on-remove="handleRemoveFile"
            :on-success="handleSuccess"
            multiple
          >
            <i-button type="ghost" icon="ios-cloud-upload-outline"></i-button>
          </Upload>
        </Form-item>
        <Form-item label="上线">
          <i-select v-model="addForm.is_online" placeholder="是否上线">
            <i-option value="0">下线</i-option>
            <i-option value="1">上线</i-option>
          </i-select>
        </Form-item>
        <Form-item label="轮播描述片" prop="desc">
          <i-input
            v-model="addForm.desc"
            type="textarea"
            :autosize="{minRows: 2,maxRows: 5}"
            placeholder="请输入轮播描述片信息"
          ></i-input>
        </Form-item>
      </i-form>
      <div slot="footer">
        <i-button type="primary" @click="handleSubmit()">提交</i-button>
        <i-button type="ghost" @click="handleReset()" style="margin-left: 8px">重置</i-button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { get } from "../../utils/request";
import { post } from "../../utils/request";
import { del } from "../../utils/request";

export default {
  data() {
    return {
      // 表格列数据
      columns: [
        {
          title: "编号",
          key: "id",
          sortable: true,
          width: 80
        },
        {
          title: "图片预览",
          render: (h, params) => {
            return h("img", {
              attrs: {
                src: params.row.url
              },
              style: {
                width: "70px"
              }
            });
          }
        },
        {
          title: "标题",
          key: "text"
        },
        {
          title: "图片地址",
          key: "url"
        },
        {
          title: "是否上线",
          key: "is_online",
          render: (h, params) => {
            let text = params.row.is_online === 0 ? "已下线" : "已上线";
            let color = params.row.is_online === 0 ? "red" : "green";
            return h("tag", {
              props: {
                color: color,
                // closable: true
              },
              style: {

              },
              on: {
                click: () => {
                  this.show(params.index);
                }
              }
            }, text);
          }
        },
        {
          title: "图片描述",
          key: "desc"
        },
        {
          title: "创建时间",
          key: "create_time",
          width: 150
        },
        {
          title: "更新时间",
          key: "update_time",
          width: 150
        },
        {
          title: "操作",
          key: "action",
          width: 180,
          align: "center",
          // 必须使用箭头函数，否则无法使用this
          render: (h, params) => {
            return h("div", [
              h(
                "i-button",
                {
                  style: {
                    margin: "0"
                  },
                  props: {
                    type: "primary",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.show(params.index);
                    }
                  }
                },
                "查看"
              ),h(
                "i-button",
                {
                  style: {
                    margin: "5px"
                  },
                  props: {
                    type: "warning",
                    size: "small" 
                  },
                  on: {
                    click: () => {
                      this.show(params.index);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "i-button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row.id);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ],
      // 表格数据
      img_list: [],
      // 查询对象
      queryInfo: {
        key: "",
        currentPage: 1,
        pageSize: 10
      },
      // 数据总数
      total: 0,
      // 查看对话框的显示/隐藏
      showMenuDetailVisible: false,
      // 搜索的关键字
      searchKey: "",
      // 添加对话框的显示/隐藏
      showMenuAddVisible: false,
      // 添加表单对象
      addForm: {
        text: "轮播图",
        img: "",
        is_online: "0",
        desc: "轮播图1"
      },
      // 添加菜单项表单验证对象
      addFormRules: {
        text: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        url: [{ required: true, message: "地址不能为空", trigger: "blur" }],
        desc: [
          { required: true, message: "请输入菜单项描述信息", trigger: "blur" }
        ]
      },
      parentDisable: false
    };
  },
  methods: {
    // 显示详情
    show(index) {
      this.$Modal.info({
        title: "详细信息",
        content: `
        标题：${this.img_list[index].text}<br>
        图片地址：${this.img_list[index].url}<br>
        是否上线：${
          this.img_list[index].is_online === 0 ? "未上线" : "已上线"
        }<br>
        描述信息：${this.img_list[index].desc}<br>
        创建时间：${this.img_list[index].create_time}<br>
        更新时间：${this.img_list[index].update_time}
        `
      });
    },
    // 删除菜单项
    remove(index) {
      this.$Modal.confirm({
        title: "删除确认",
        content: "<p>该操作不可逆，数据将被永久删除</p><p>确定删除？</p>",
        okText: "确定删除",
        cancelText: "取消",
        onOk: () => {
          del("/adv/delete/" + index)
            .then(res => {
              this.$Message.success("删除成功！");
              this.getImgData();
            })
            .catch(err => {
              this.$Message.error("删除失败！");
            });
        },
        onCancel: () => {}
      });
    },
    // 获取菜单数据
    getImgData() {
      get("/adv/index_imgs", this.queryInfo)
        .then(res => {
          this.img_list = res.data.imgs;
          this.total = res.data.total;
        })
        .catch(err => {
          this.$Message.error("获取数据失败");
        });
    },
    // 页码改变
    handlePageChange(newPage) {
      this.queryInfo.currentPage = newPage;
      this.getImgData();
    },
    // 页大小改变
    handelPageSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getImgData();
    },
    // 查看菜单项点击确定/取消的回调
    checkOk() {},
    checkCancel() {},
    // 搜索
    search() {
      this.getImgData();
    },
    // 搜索框清空后，加载全部数据
    clearInput() {
      if (!this.queryInfo.key) {
        this.getImgData();
      }
    },
    handleSubmit() {
      this.$refs.addFormRef.validate(valid => {
        if (valid) {
          post("/adv/add", this.addForm)
            .then(res => {
              this.$Message.success("添加成功!");
              this.showMenuAddVisible = false;
              this.getImgData();
            })
            .catch(err => {
              this.$Message.error("添加失败!");
            });
        }
      });
    },
    //重置表单
    handleReset() {
      this.$refs.addFormRef.resetFields();
    },
    showAddModal() {
      this.showMenuAddVisible = true;
    },
    handleMenuLevelSelect(selectValue) {
      // 创建的菜单时一级菜单时，禁止选择父级菜单
      if (selectValue === "0") {
        this.parentDisable = true;
        this.addForm.parent_id = "";
      } else {
        this.parentDisable = false;
      }
    },
    addModalVisibleChange() {
      this.$refs.addFormRef.resetFields();
    },

    // 图片上传处理
    handleFormatError(file) {
      this.$Notice.warning({
        title: "文件格式不正确",
        desc:
          "文件 " + file.name + " 格式不正确，请上传 jpg 或 png 格式的图片。"
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "超出文件大小限制",
        desc: "文件 " + file.name + " 太大，不能超过 2M。"
      });
    },
    handleRemoveFile(file, fileList) {
      console.log(file);
      console.log(fileList);
    },
    handleSuccess(response, file, fileList) {
      this.addForm.img = file.name;
    }
  },
  created() {
    this.getImgData();
  },
  //计算属性
  computed: {
    getRootMenus() {
      let resData = [];
      this.img_list.forEach(item => {
        if (item.parent_id === 0) {
          resData.push(item);
        }
      });
      return resData;
    }
  }
};
</script>
<style lang="less" scoped>
// .menu-list{

// }
.col {
  line-height: 30px;
}
.input-col {
  margin-right: 20px;
}
.table {
  margin: 20px 0px;
}
</style>